using JGSY.CourseManagement.Infrastructure.Configuration;
using System;
using System.Collections.Generic;
using System.IO;
using System.Text.Json;

namespace JGSY.CourseManagement.Infrastructure.Services
{
    /// <summary>
    /// 基于JSON文件的配置服务实现，提供配置数据的持久化存储 
    /// </summary>
    public class JsonConfigurationService : IConfigurationService
    {
        /// <summary>
        /// 配置文件路径
        /// </summary>
        private readonly string _configFilePath;
        /// <summary>
        /// 内存中的配置键值对集合
        /// </summary>
        private Dictionary<string, object> _settings = new Dictionary<string, object>();

        /// <summary>
        /// 初始化JsonConfigurationService实例
        /// </summary>
        /// <param name="configFilePath">JSON配置文件的完整路径</param>
        /// <exception cref="ArgumentNullException">当configFilePath为null时抛出</exception>
        public JsonConfigurationService(string configFilePath)
        {
            _configFilePath = configFilePath ?? throw new ArgumentNullException(nameof(configFilePath));
        }

        /// <summary>
        /// 从配置中获取指定键的值
        /// </summary>
        /// <typeparam name="T">值的目标类型</typeparam>
        /// <param name="key">配置键</param>
        /// <returns>转换后的配置值；若键不存在则返回类型默认值</returns>
        public T GetValue<T>(string key)
        {
            if (_settings.TryGetValue(key, out var value))
            {
                return (T)Convert.ChangeType(value, typeof(T));
            }

            return default;
        }

        /// <summary>
        /// 设置配置中指定键的值（仅更新内存，需调用Save()持久化）
        /// </summary>
        /// <typeparam name="T">值的类型</typeparam>
        /// <param name="key">配置键</param>
        /// <param name="value">要设置的值</param>
        public void SetValue<T>(string key, T value)
        {
            _settings[key] = value;
        }

        /// <summary>
        /// 将内存中的配置数据保存到JSON文件
        /// </summary>
        /// <exception cref="Exception">当保存失败时抛出，包含内部异常信息</exception>
        public void Save()
        {
            try
            {
                var json = JsonSerializer.Serialize(_settings, new JsonSerializerOptions { WriteIndented = true });
                File.WriteAllText(_configFilePath, json);
            }
            catch (Exception ex)
            {
                throw new Exception("Failed to save configuration", ex);
            }
        }

        /// <summary>
        /// 从JSON文件加载配置数据到内存
        /// </summary>
        /// <exception cref="Exception">当加载失败时抛出，包含内部异常信息</exception>
        public void Load()
        {
            try
            {
                if (File.Exists(_configFilePath))
                {
                    var json = File.ReadAllText(_configFilePath);
                    _settings = JsonSerializer.Deserialize<Dictionary<string, object>>(json);
                }
            }
            catch (Exception ex)
            {
                throw new Exception("Failed to load configuration", ex);
            }
        }
    }
}